package tmt.usercenter.web.controller;

import com.tmt.annotation.ScopeDescriptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import tmt.usercenter.web.common.Utils;
import tmt.usercenter.web.domain.ClientSystem;
import tmt.usercenter.web.service.AuthScopeService;
import tmt.usercenter.web.service.ClientSystemService;
import tmt.usercenter.web.vo.ScopeVo;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Component
@ScopeDescriptor(value = "user_photo", title = "用户图片", description = "获取用户图片", order = 2)
class UserPhoto {
}

@Component
@ScopeDescriptor(value = "user_message", title = "用户消息", description = "获取、发送用户消息", order = 2)
class UserMessage {
}

@Controller
@SessionAttributes("authorizationRequest")
public class Oauth2Controller {

	@Autowired
	private ClientSystemService clientService;
	@Autowired
	private ApplicationContext applicationContext;
	@Autowired
	private AuthScopeService authScopeService;

	@RequestMapping("/oauth/confirm_access")
	public String getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
		AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");

		if (authorizationRequest == null) {
			throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
		}

		ClientSystem clientSystem = clientService.findByClientId(authorizationRequest.getClientId());
		model.put("client", clientSystem);

		if (request.getAttribute("_csrf") != null) {
			model.put("_csrf", request.getAttribute("_csrf"));
		}

		// oauth2 要求的 scope.[scope_name] : false
		Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request.getAttribute("scopes"));

		/*
			1. 获取所有的 scopes 信息，包含是否是默认选中的
			2. 循环请求的 scopes 信息，构造返回数据
		 */
		List<String> scopesStringList = scopes.keySet().stream().map(s -> s.replace("scope.", "")).collect(Collectors.toList());
		if (!scopesStringList.isEmpty()) {
			List<ScopeDescriptor> descriptors = Utils.getAllScopes(applicationContext);
			List<ScopeVo> allScopeList = new ArrayList<>();
			descriptors.stream()
					.sorted(Comparator.nullsLast(Comparator.comparing(ScopeDescriptor::order)))
					.forEachOrdered(x -> allScopeList.add(new ScopeVo(x.title(), x.value(), x.description(), x.order(), x.defaultSelected())));
			List<ScopeVo> scopesList = allScopeList.stream()
					.filter(c -> scopesStringList.contains(c.getValue().toString()))
					.collect(Collectors.toList());
			List<ScopeVo> scopeVoList = new ArrayList<>();
			for (ScopeVo scope : scopesList) {
				ScopeVo vo = new ScopeVo(scope.getTitle(), scope.getValue(), scope.getDescription(), scope.getSort(), scope.isDefaultSelected());

				if (scopesStringList.contains(scope.getValue().toString())) {
					vo.setSelected(true);
				} else {
					if (scope.isDefaultSelected()) {
						vo.setSelected(true);
					} else {
						vo.setSelected(false);
					}
				}

				scopeVoList.add(vo);
			}

			model.put("scopes", scopeVoList);
		}

		return "user/confirm_access";
	}


}
